package com.cn.sl.server.config.websocket

import cn.dev33.satoken.SaManager
import com.cn.sl.server.common.constant.Constant
import org.dromara.hutool.core.text.CharSequenceUtil
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.messaging.Message
import org.springframework.messaging.MessageChannel
import org.springframework.messaging.simp.stomp.StompCommand
import org.springframework.messaging.simp.stomp.StompHeaderAccessor
import org.springframework.messaging.support.ChannelInterceptor
import org.springframework.messaging.support.ErrorMessage
import org.springframework.messaging.support.MessageHeaderAccessor
import org.springframework.web.bind.annotation.ControllerAdvice

/**
 * @author 阮雪峰
 */
class WebSocketHandleInterceptor : ChannelInterceptor {

    val log: Logger = LoggerFactory.getLogger(ControllerAdvice::class.java)
    override fun preSend(message: Message<*>, channel: MessageChannel): Message<*> {
        val accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor::class.java)!!
        val token: String? = accessor.getFirstNativeHeader(Constant.TOKEN)
        if (StompCommand.CONNECT == accessor.command) {
            if (CharSequenceUtil.isBlank(token)) {
                return ErrorMessage(RuntimeException("非法用户"))
            }
            // 绑定user
            val stringUserId: String = SaManager.getSaTokenDao()
                .get(String.format("%s:login:token:%s", SaManager.getConfig().tokenName, token))
            log.info("用户[{}]成功连接。。。", stringUserId)
            if (CharSequenceUtil.isBlank(stringUserId)) {
                return ErrorMessage(RuntimeException("非法用户"))
            }
        } else if (StompCommand.DISCONNECT == accessor.command) {
            if (CharSequenceUtil.isBlank(token)) {
                return ErrorMessage(RuntimeException("非法用户"))
            }
            // 绑定user
            val stringUserId: String = SaManager.getSaTokenDao()
                .get(String.format("%s:login:token:%s", SaManager.getConfig().tokenName, token))
            log.info("用户[{}]断开连接。。。", stringUserId)
        }
        return message
    }
}
